import {common} from '../model/index.js'
import fetch from "node-fetch";
import plugin from '../../../lib/plugins/plugin.js'

const apis = [
    'http://api.tencent-qq.cn/api/imgapi.php', //Yize
    'https://api.yimian.xyz/img', //Ushio
    'https://t.lizina.top/mp', //lizina.top
    'https://moe.anosu.top/img',  //Anosu
    'https://moe.jitsu.top/api/?sort=jitsu', //jitsu
]

let useapi = apis

export class xy_sjt extends plugin {
    constructor() {
        super({
            name: '云溪院随机图',
            dsc: '随机图',
            event: 'message',
            priority: 110,
            rule: [{
                reg: '^#?来点随机图(\\d+张)?$',
                fnc: 'txsjt'
            }]
        })
    }

    async txsjt(e) {
        let image = []
        let res = []
        let img
        let number = e.msg.match(/\d+/)
        if (number) {
            number = Number(number[0])
            number = number < 2 ? 2 : number > 10 ? 10 : number
        } else {
            number = 1
        }
        for (let i = 0; i < number; i++) {
            let flag = 1
            img = await getImg(e)
            if (!img.includes('http')) {
                img = 'https:' + img
            }

            if (i == 0) {
                res.push(img)
                image.push(segment.image(img))
            } else {
                for (let val of res) {
                    if (val == img) {
                        flag = 0
                    }
                }
                if (flag == 1) {
                    image.push(segment.image(img))
                } else {
                    number++
                }
            }

        }
        //logger.mark(number)
        if(e.isGroup) {
            number > 1 ? common.getforwardMsg(e, image, '点击显示云溪院随机图', 0, false, true) : e.reply(image)
        }else{
            for (let i = 0; i < image.length; i++){
                e.reply(image[i])
            }
        }
    }
}

async function getImg(e) {
    let res = await response()
    let i = 0
    while (!res && i < apis.length) {
        res = await response()
        i++
    }
    if (i > apis.length) return e.reply('接口失效')
    let img = res.img || res.imgurl || res.pic?.[0] || res
    return img
}


async function response() {
    let num = Math.round(Math.random() * (useapi.length - 1))
    logger.warn(`尝试请求接口:${useapi[num]}`)
    try {
        let res = await fetch(useapi[num])
        if (!res.ok) {
            logger.warn(useapi[num] + '，接口失效')
            useapi.splice(num, 1)
            return false
        }
        if (res.headers.get('content-type').includes('json')) {
            res = await res.json()
            return res
        }
        return useapi[num]
    } catch (err) {
        logger.warn(useapi[num] + '，接口失效')
        useapi.splice(num, 1)
        return false
    }
}